//
//  JTSettingManager.m
//  AFNetworking
//
//  Created by 黄金台 on 2019/8/18.
//

#import "JTSettingManager.h"
#import "NSBundle+Language.h"

NSString * const JTLanguageZh_Hans = @"zh-Hans";    // 中文简体
NSString * const JTLanguageZh_Hant = @"zh-Hant";    // 中文繁体
NSString * const JTLanguageEn = @"en";              // 英文
NSString * const JTLanguageEs = @"es";              // 葡萄牙语

static NSString * const JTLanguageOptionKey = @"JTLanguageOptionKey";

@interface JTSettingManager ()

@end

static JTSettingManager *__settingManager = nil;

@implementation JTSettingManager

+ (instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __settingManager = [[JTSettingManager alloc] init];
    });
    return __settingManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self loadSetting];
    }
    return self;
}

- (void)loadSetting
{
    NSString *userLanguage = [[NSUserDefaults standardUserDefaults] objectForKey:JTLanguageOptionKey];
    // 使用用户设置的语言
    if (userLanguage && userLanguage.length > 0) {
        if ([userLanguage isEqualToString:JTLanguageZh_Hans]) {
            _language = JTLanguageZh_Hans;
        }
        else if ([userLanguage isEqualToString:JTLanguageZh_Hant]) {
            _language = JTLanguageZh_Hant;
        }
        else if ([userLanguage isEqualToString:JTLanguageEs]) {
            _language = JTLanguageEs;
        }
        else {
            _language = JTLanguageEn;
        }
    }
    // 跟随系统语言
    else {
        NSString *systemLanguage = [[NSLocale preferredLanguages] firstObject];
        if ([systemLanguage hasPrefix:JTLanguageZh_Hans]) {
            _language = JTLanguageZh_Hans;
        }
        else if ([systemLanguage hasPrefix:JTLanguageZh_Hant]) {
            _language = JTLanguageZh_Hant;
        }
        else if ([systemLanguage hasPrefix:JTLanguageEs]) {
            _language = JTLanguageEs;
        }
        else {
            _language = JTLanguageEn;
        }
    }
}

// 设置app语言
- (void)setAppLanguage:(JTLanguageName)language
{
    if ([language isEqualToString:JTLanguageZh_Hans] ||
        [language isEqualToString:JTLanguageZh_Hant] ||
        [language isEqualToString:JTLanguageEs] ||
        [language isEqualToString:JTLanguageEn])
    {
        [[NSUserDefaults standardUserDefaults] setObject:language forKey:JTLanguageOptionKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        _language = language;
        
        // 设置语言
        [NSBundle setLanguage:language];
    }
    else {
        NSLog(@"=========== You can not set language beyond the bounds of these four language, it is not supported =========");
    }
}

@end
